import * as React from 'react';

import {MenuItem} from "./menu-item";

export interface MenuProps {
    items: any[];
    className?: string;
    selected?: string;
    onClick?: (name:string) => void;
}

export interface MenuState {
    selected?: string;
    hidden?: string;
}

export class Menu extends React.Component<MenuProps, MenuState> {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            selected: props.selected || '',
        } as any;
    }

    handleClick(name) {
        this.setState({
            selected: name
        });

        if (this.props.onClick) {
            this.props.onClick(name);
        }
    }

    renderItem(item, i) {
        let {className = 'media-menu-item'} = item;

        if (item.name === this.state.selected) {
            className += ' active';
        }
        if (item.name === this.state.hidden) {
            className += ' hidden';
        }
        return <MenuItem {...item} className={className} onClick={this.handleClick} key={i} />
    }

    render() {
        let items = this.props.items.sort((a, b)=> {
            let aPriority  = a.priority || 0;
            let bPriority  = b.priority || 0;
            if (aPriority > bPriority) {
                return 1;
            } else if (aPriority < bPriority) {
                return -1;
            } else {
                return 0;
            }
        });

        let {className = 'menu'} = this.props;

        return (
            <div className={className}>
                {items.map((item, i)=> {
                    return this.renderItem(item, i);
                })}
            </div>
        )
    }
}
